<?php


$GLOBALS['USE_MYSQLI']=false;


//判断php版本
if(phpversion()>=5.5){
    $GLOBALS['USE_MYSQLI']=true;
}


//创建全局变量DB引用global配置文件参数
$GLOBALS['DB']=new DB
(
    $GLOBALS['db_configs']['main'][$GLOBALS['ENVIRONMENT']]['host'],
    $GLOBALS['db_configs']['main'][$GLOBALS['ENVIRONMENT']]['user'],
    $GLOBALS['db_configs']['main'][$GLOBALS['ENVIRONMENT']]['pass'],
    $GLOBALS['db_configs']['main'][$GLOBALS['ENVIRONMENT']]['dbName']
);


//封装数据库连接函数
class DB {
    private $host;
    private $user;
    private $pass;
    private $dbName;
    private $maxConnectionTries;
    private $connectionTried;
    public  $connection;
    private $connectionError;
    private $hasConnection;
    //构造方法,对象创建时调用
    function __construct($host,$user,$pass,$dbName){
        $this->host=$host;
        $this->user=$user;
        $this->pass=$pass;
        $this->dbName=$dbName;
        $this->hasConnection=false;
        $this->connectionTried=0;
    }

    //析构函数,对象销毁时调用
    function __descruct(){
        if ($this->hasConnection || is_object($this->connection)){
            //根据PHP版本调用mysql关闭连接函数
            if ($GLOBALS['USE_MYSQLI']){
                mysqli_close($this->connection);
            }else{
                mysql_close($this->connection);
            }
        }
    }

    //手动关闭数据库连接
    function close(){
        if ($this->hasConnection || is_object($this->connection)) {
            //根据PHP版本调用mysql关闭连接函数
            if ($GLOBALS['USE_MYSQLI']){
                mysqli_close($this->connection);
            }else{
                mysql_close($this->connection);
            }
        }
    }

    //获取数据库连接
    function connect(){
        //根据版本不同执行不同函数连接数据库
        if ($GLOBALS['USE_MYSQLI']){
            //问题1:这里为什么要拼接'p:'
            //问题2:为什么要使用$this->host而不是$host
            if (!$this->connection = mysqli_connect('p:'.$this->host,$this->user,$this->pass,$this->dbName)){
                //连接数小于最大连接的时候才获取连接
                if ($this->connectionTried<DB_MAX_CONNECTION_TRIES){
                    sleep(1);
                    $this->connectionTried++;
                    $this->connect();
                    return;
                }else{
                    //创建错误信息
                    trigger_error("无法连接数据库:".$this->host,E_USER_NOTICE);
                    //error_display(ERROR_MAINTANENCE);
                    exit;
                }
            }
            //如果变量不存在或者变量为dev,执行sql,"SET NAMES 'utf8'",用于保证不会出现乱码
            //问题3:这里为什么要在本地数据库的时候才执行"SET NAMES 'utf8'"
            if (!isset($GLOBALS['ENVIRONMENT']) || $GLOBALS['ENVIRONMENT']=='dev'){
                mysqli_query($this->connection,"SET NAMES 'utf8'");
            }
        }else{
            if (!$this->connection = mysql_connect($this->host,$this->user,$this->pass,true)){
                if ($this->connectionTried<DB_MAX_CONNECTION_TRIES){
                    sleep(1);
                    $this->connectionTried++;
                    $this->connect();
                    return;
                }else{
                    trigger_error("无法连接数据库:: ".$this->host, E_USER_NOTICE);
                    //error_display(ERROR_MAINTANENCE);
                    exit;
                }
            }
            if (!isset($GLOBALS['ENVIRONMENT']) || $GLOBALS['ENVIRONMENT'] == 'dev'){
                mysql_query("SET NAMES 'utf8'");
            }
            //选择数据库
            if (!mysql_select_db($this->dbName,$this->connection)){
                //创建错误信息
                trigger_error("无法连接数据库:".$this->host.":".$this->dbName,E_USER_NOTICE);
                //error_display(ERROR_MAINTANENCE);
                exit;
            }
        }
        //更改布尔值为true
        $this->hasConnection=true;
    }

    //检查连接,如果连接不存在,则重新获取连接
    function checkConnection(){
        if (!$this->hasConnection){
            $this->connect();
        }
    }

    //封装query方法
    public function query($sql){
        $this->checkConnection();
        if ($GLOBALS['USE_MYSQLI']){
            if (!$result=mysqli_query($this->connection,$sql)){
                trigger_error("无法查询:".$this->host.":".$this->dbName." ".$sql,E_USER_NOTICE);
                return false;
            }
        }else{
            if (!$result=mysql_query($sql,$this->connection)){
                trigger_error("无法查询: ".$this->host.":".$this->dbName." ".$sql, E_USER_NOTICE);
                return false;
            }
        }
        //如果执行成功则返回MR对象
        return new MR($this, $result);
    }
}

//封装数据库操作函数
class MR {
    private $mysqlResult;
    private $query;

    function __construct(&$mysqlResult,$query){
        $this->mysqlResult = &$mysqlResult;
        $this->query = $query;
    }

    //从当前数据指针中获取关联数组
    public function fetch(){
        if ($GLOBALS['USE_MYSQLI']){
            // 参数2有3个选择
            // MYSQL_ASSOC - 关联数组
            // MYSQL_NUM - 数字数组
            // MYSQL_BOTH - 默认。同时产生关联和数字数组
            if ($row = mysqli_fetch_array($this->query,MYSQLI_ASSOC)){
                return $row;
            }
            elseif ($this->size() > 0){
                mysqli_data_seek($this->query,0);
                return false;
            }
            else{
                return false;
            }
        }else{
            if ($row = mysql_fetch_array($this->query,MYSQLI_ASSOC)){
                return $row;
            }
            elseif ($this->size() > 0){
                mysql_data_seek($this->query,0);
                return false;
            }
            else{
                return false;
            }
        }
    }
    //获取当前数据指针的size
    public function size(){
        if ($GLOBALS['USE_MYSQLI']){
            return mysqli_num_rows($this->query);
        }else{
            return mysql_num_rows($this->query);
        }
    }
    //获取受影响的行数
    public function rowsAffected(){
        if ($GLOBALS['USE_MYSQLI']){
            return mysqli_affected_rows($this->mysqlResult->connection);
        }else{
            return mysql_affected_rows($this->mysqlResult->connection);
        }
    }
    //获取最后一次插入操作所自动生成的id
    public function insertID(){
        if ($GLOBALS['USE_MYSQLI']){
            return mysqli_insert_id($this->mysqlResult->connection);
        }else{
            return mysql_insert_id($this->mysqlResult->connection);
        }
    }
}

//开始方法
function _core_main()
{
    mods('main,wode,xinjian,daifankui,shencha,jiaoban,banli,yiban,suoyou,weiyuan,xinxi,xitong,login');
    initSession();
    //func('auth, menu');
    if(!empty($_SESSION['USERID'])){
        $data = getUserInfo($_SESSION['USERID']);
        $GLOBALS['USERINFO'] = $data;
    }
    _core_load();
}

//加载
function _core_load()
{
    if (!empty($_REQUEST['action'])){
        $GLOBALS['ACTION'] = $_REQUEST['action'];
    }else{
        $GLOBALS['ACTION'] = 'login';
    }
    //这里取出action参数,根据参数调用相应的方法
    //如果action为空,则设置为默认Action

    if(empty($GLOBALS['ACTION'])){
        if (empty($_SESSION['USERID'])){
            //这里统一处理, 没有登录信息的情况下,统一跳转登录页
            call_user_func_array("login_default",array());
            exit();
        }else{
            $params_action = "main_default";
            $GLOBALS['ACTION'] = 'main';
            //判断是否存在此方法
            if (function_exists($params_action)){
                call_user_func_array($params_action,array());
            }
        }

    }else{
        $params_action = '';
        //判断是页面请求还是数据请求
        if (strpos($GLOBALS['ACTION'],'api_') !== false){
            //数据请求
            $params_action = $GLOBALS['ACTION'];
        } else{
            //页面请求
            if (empty($_SESSION['USERID'])){
                //这里统一处理, 没有登录信息的情况下,统一跳转登录页
                call_user_func_array("login_default",array());
                exit();
            }else{
                $params_action = $GLOBALS['ACTION']."_default";
            }
        }
        //判断是否存在此方法
        if (function_exists($params_action)){
            call_user_func_array($params_action,array());
            if (!empty($_REQUEST['taskid'])){
                $sql = "update task set isLook=1 where id=".$_REQUEST['taskid'];
                $GLOBALS['DB']->query($sql);
            }
        }else{
            $str = array("code"=>"1","message"=>"action错误");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            exit();
        }
    }
}

/**
 * 根据ID获取用户信息
 * @param $userid
 * @return array
 */
function getUserInfo($userid){
    $data = array();
    $sql = "select * from user where id = ".$userid;
    $result =  $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

/**
 * 根据ID获取提案信息
 * @param $proposalId
 * @return mixed
 */
function getProposalInfo($proposalId){
    $data = array();
    $sql = "select * from proposal where id = ".$proposalId;
    $result =  $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

/**
 *根据主办单位ID获取此主办单位的所有提案
 * @param $sponsor
 * @return mixed
 */
function getSponsor($sponsor){
    $data = array();
    $sql = "select * from proposal where sponsor = ".$sponsor;
    $result =  $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

/**
 * 获取关于某个提案的所有操作记录
 * @param $proposalId
 * @return array
 */
function getProposalRecord($proposalId){
    $data = array();
    $sql = "select * from record where proposalid='".$proposalId."'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

/**
 * 获取某个提案是不是重点提案
 * @param $id
 * @return array
 */
function getStressToProposal($id){
    $data = array();
    $sql = "select stress from proposal where id='".$id."'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

/**
 * 根据id获取操作记录
 * @param $id
 * @return array
 */
function getRecordToId($id){
    $data = array();
    $sql = "select * from record where id=".$id;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

/**
 * 获取关于某个提案最近操作的一次操作记录
 * @param $proposalId
 * @return array
 */
function getProposalRecordToLast($proposalId){
    $data = array();
    $sql = "select * from record where proposalid='".$proposalId."' order by id desc limit 1";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

/**
 * 获取某个提案待交办状态的信息
 * @param $proposalId
 * @return array
 */
function getProposalRecordToDaiJiaoBan($proposalId){
    $data = array();
    $sql = "select * from record where proposalid='".$proposalId."' and  operatetype='2'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

/**
 * 获取协办单位
 * @param $assistID
 * @return array
 */
function getAssistUnitToID($assistID){
    $data = array();
    $sql = "select * from assist_unit where id='".$assistID."'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}



/**
 * 根据ID获取主办单位
 * @param $sponsorID
 * @return array
 */
function getSponsorUnitToID($sponsorID){
    $data = array();
    $sql = "select * from sponsor_unit where id=".$sponsorID;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}


/**
 * 更新操作记录
 * @param $proposalid   要操作的提案id
 * @param $operateid  操作人id
 * @param $recordState  当前执行的操作
 * @param $remarks 备注信息,可为空,为空时默认取出上一条操作记录中的备注插入
 */
function updateRecord($proposalid,$operateid,$recordState,$remarks){

    //操作时间
    $operatetime = date("Y-m-d H:i:s",time());
    $userData = getUserInfo($operateid);
    $operatename = $userData['realname'];

    $data = array();
    $sql = "select * from record where proposalid='".$proposalid."' order by id desc limit 1";
    $result=$GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }

    if (!empty($data)){
        $lastTime = $data['operatetime'];
        $day = floor((strtotime($operatetime) - strtotime($lastTime))/86400);
        $hours = floor((strtotime($operatetime) - strtotime($lastTime))%86400/3600);
        $minute = floor((strtotime($operatetime) - strtotime($lastTime))%86400%3600/60);

        if ($day == 0 && $hours == 0){
            $haoshi = $minute."分钟";
        }
        else if ($day == 0){
            $haoshi = $hours."小时".$minute."分钟";
        }
        else{
            $haoshi = $day."天".$hours."小时".$minute."分钟";
        }

        if (empty($remarks)){
            $remarks = $data['remarks'];
        }
    }else{
        $haoshi = '0分钟';
        if (empty($remarks)){
            $remarks = '无';
        }
    }

    $info = '暂留';
    $sql = "insert into record values(null,'".$operatetime."','".$operatename."','".$recordState."','".$haoshi."','".$remarks."','".$info."',".$proposalid.",'".$operateid."')";
    $result=$GLOBALS['DB']->query($sql);
    return $result;
}


/**
 * 获取党派列表
 * @return array
 */
function getPartyList(){
    $data = array();
    $sql = "select * from party_record";
    $result =  $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[]= $res;
    }
    return $data;
}

/**
 * 获取全部主办单位列表
 * @return array
 */
function getAllSponsorUnit(){
    $data = array();
    $sql = "select * from sponsor_unit";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

/**
 * 获取全部协办单位列表
 * @return array
 */
function getAllAssisUnit(){
    $data = array();
    $sql = "select * from assist_unit";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

/**
 * 获取全部用户组详细信息
 */
function getAllUserGroup(){
    $data = array();
    $sql = "select * from usergroup";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

/**
 * 根据id获取用户组
 */
function getUserGroupToId($id){
    $data = array();
    $sql = "select * from usergroup where id=".$id;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}


/**
 * 获取全部用户信息
 */
function getAllUserInfo(){
    $data = array();
    $sql = "select * from user";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

function getAllUserInfoOrGroupName(){
    $data = array();
    $sql = "select a.*,b.role from user as a left join usergroup as b on a.role=b.id";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

/**
 * 获取全部用户组名称
 */
function getUserGroupName(){
    $data = array();
    $sql = "select role from usergroup where id != 1";
    $result = $GLOBALS['DB']->query($sql);
    while ($res = $result->fetch()){
        $data[] = $res;
    }
    return $data;
}

/**
 * 获取所有提案数量
 * @param getStatenumNO
 * @return array
 */
function getStatenumall(){
    $data = array();
    $sql = "select count(*) as num  from proposal";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 获取所有未立案数量
 * @param getStatenumNO
 * @return array
 */
function getStatenumNO(){
    $data = array();
    $sql = "select count(*) as num  from proposal where state='2'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 获取所有已完结数量
 * @param getStatenumNO
 * @return array
 */
function getStatenumOk(){
    $data = array();
    $sql = "select count(*) as num  from proposal where state='6'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 获取所有待审查数量
 * @param getStatenumNO
 * @return array
 */
function getStatenumDaiShenCha(){
    $data = array();
    $sql = "select count(*) as num  from proposal where state='1'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 获取待交办查数量
 * @param getStatenumNO
 * @return array
 */
function getStatenumDaijiaoban(){
    $data = array();
    $sql = "select count(*) as num  from proposal where state='3'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 获取办理中查数量
 * @param getStatenumNO
 * @return array
 */
function getStatenumBanlizhong(){
    $data = array();
    $sql = "select count(*) as num  from proposal where state='4'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 修改密码
 * @param updatePwd
 * @return array
 */
function updatePwd($userid,$password){
    $data = array();
    $sql = "update user set password='".$password."' where id ='".$userid."'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 查询密码
 * @param getPwd
 * @return array
 */
function getPwd($userid){
    $data = array();
    $sql = "select password from user where id=".$userid;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}
/**
 * 修改个人资料
 * @param getPwd
 * @return array
 */
function updateProfile($userid,$work,$contact_way,$photo_url){
    $data = array();
    $sql = "update  user set work='".$work."',contact_way='".$contact_way."',photo_url='".$photo_url."' where id='".$userid."'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

//获取提案总数
function getProposalCount(){
    $data = array();
    $sql = "select count(*) as num from proposal";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

//获取委员信息
function getWeiyuanInfo(){
    $data = array();
    $sql = "select * from user where role in(2,3)";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }
    return $data;
}

//获取用户组总数
function getUserGroupCount(){
    $data = array();
    $sql = "select count(*) as num from usergroup";
    $result =  $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

//获取某条任务信息
function getTaskToId($id){
    $data = array();
    $sql = "select * from task where id=".$id;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    return $data;
}

?>